package com.hqu.ms.nearby;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.googlecode.androidannotations.annotations.Background;
import com.googlecode.androidannotations.annotations.Click;
import com.googlecode.androidannotations.annotations.EFragment;
import com.googlecode.androidannotations.annotations.UiThread;
import com.googlecode.androidannotations.annotations.ViewById;
import com.googlecode.androidannotations.annotations.sharedpreferences.Pref;
import com.handmark.pulltorefresh.extras.listfragment.PullToRefreshListFragment;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.hqu.ms.MSApp;
import com.hqu.ms.MultiLocationActivity_;
import com.hqu.ms.R;
import com.hqu.ms.detail.DetailActivity_;
import com.hqu.ms.entities.NearbyPrefs_;
import com.hqu.ms.entities.StoreEntivity;
import com.hqu.ms.entities.UserPrefs_;
import com.hqu.ms.entities.ViewHolder;
import com.hqu.ms.ui.view.MSPullToRefreshView;
import com.hqu.ms.utils.JSONResponse;
import com.hqu.ms.utils.JSONResponse.Status;
import com.hqu.ms.utils.JSONUtil;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

@EFragment(R.layout.ms_nearby_fragment)
public class NearbyFragment extends PullToRefreshListFragment implements OnLastItemVisibleListener,
	OnRefreshListener<ListView>, OnItemClickListener{

	private MSPullToRefreshView mListView;
	private NearbyArrayAdapter adapter;
	private List<StoreEntivity> stores = new ArrayList<StoreEntivity>();
	
	UserPrefs_ userPrefs;
	
	@Pref
	NearbyPrefs_ nearbyPrefs;
	
	@ViewById
	TextView title;
	@ViewById
	RelativeLayout titleLayout;
	
	private boolean showDistance = true;
	public PopupWindow popWindow;
	
	private enum types{NEAR, LIKES, CONFIRM};
	private types current = types.NEAR;
	
	@Click(R.id.map_switch)
	void switchMap(){
		MultiLocationActivity_.intent(getActivity()).start();
		getActivity().overridePendingTransition(R.anim.base_slide_right_in, R.anim.base_stay_orig);
	}
	
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		ViewHolder holder = (ViewHolder) view.getTag();
		if(holder == null){
			return ;
		}else {
//			Log.d("onItemClicked", holder.store.toString());
			DetailActivity_.intent(getActivity()).store(holder.store).start();
			getActivity().overridePendingTransition(R.anim.base_slide_right_in, R.anim.base_stay_orig);
		}
	}

	@Override
	public void onRefresh(PullToRefreshBase<ListView> refreshView) {
		getNearbyInfo(true, order_way);
	}

	@Override
	public void onLastItemVisible() {
		getNearbyInfo(false, order_way);
	}
	
	@Override
	protected PullToRefreshListView onCreatePullToRefreshListView(
			LayoutInflater inflater, Bundle savedInstanceState) {
		MSPullToRefreshView view = new MSPullToRefreshView(getActivity());
		view.addFootView(R.layout.progress_bar);	
		return view;
	}

	
	@Override
	public View myCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.ms_nearby_fragment, null);
	}
	
	void saveListviewState() {
		// Save last state
		if(adapter.getCount()>2){
			int pos = mListView.getRefreshableView().getFirstVisiblePosition();
			nearbyPrefs.edit().listViewSaveState().put(pos).apply();
		}
	}
	
	void initListView() {
		Log.d("Nearby", "begin initListView ...");
		
		mListView = (MSPullToRefreshView) getPullToRefreshListView();
		mListView.getRefreshableView().setTranscriptMode(AbsListView.TRANSCRIPT_MODE_NORMAL);
		mListView.setOnLastItemVisibleListener(this);
		mListView.setOnRefreshListener(this);
		mListView.setOnItemClickListener(this);
		adapter = new NearbyArrayAdapter(getActivity(), stores, showDistance);
		mListView.setAdapter(adapter);
		Log.d("Nearby", "initListView ...");
	}
	

	@Click
	void titleClicked(){
		if(popWindow != null && popWindow.isShowing()){
			popWindow.dismiss();
			popWindow = null;
			return;
		}
		showPopWindow();
	}
	
	public void showPopWindow() {
		
		if (popWindow == null) {
			popWindow = new PopupWindow(getActivity());
			popWindow.setBackgroundDrawable(null);
			popWindow.setOutsideTouchable(true);
			View  popView = getActivity().getLayoutInflater().inflate(R.layout.ms_nearby_pop, null);
			popWindow.setContentView(popView);
			popWindow.setWidth(LayoutParams.WRAP_CONTENT);
			popWindow.setHeight(LayoutParams.WRAP_CONTENT);
			Button nearbyBtn = (Button)popView.findViewById(R.id.nearbyBtn);
			Button nearbyLikesBtn = (Button)popView.findViewById(R.id.nearby_likes);
			Button nearbyConfirm = (Button)popView.findViewById(R.id.nearby_confirm);
			nearbyBtn.setOnClickListener(clickListeners);
			nearbyConfirm.setOnClickListener(clickListeners);
			nearbyLikesBtn.setOnClickListener(clickListeners);
			
		}
		
		popWindow.showAtLocation(titleLayout, Gravity.TOP, 0, 2*title.getHeight()+15);
	}

	
	View.OnClickListener clickListeners = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			popWindow.dismiss();
			popWindow = null;
			switch (v.getId()) {
			case R.id.nearbyBtn:
				if(current == types.NEAR){
					return ;
				}
				
				title.setText(getString(R.string.nearby_tips_near));
				getNearbyInfo(true, 2);
				order_way = 2;
				current = types.NEAR;
				break;
			case R.id.nearby_confirm:
				if(current == types.CONFIRM){
					return ;
				}
				title.setText(getString(R.string.nearby_tips_confirm));
				getNearbyInfo(true, 3);
				order_way = 3;
				current = types.CONFIRM;
				break;
			case R.id.nearby_likes:
				if(current == types.LIKES){
					return ;
				}
				title.setText(getString(R.string.nearby_tips_likesort));
				getNearbyInfo(true, 1);
				order_way = 1;
				current = types.LIKES;
				break;
			default:
				break;
			}
			
			
		}
	};
	
	
	private int page = 1;
	int order_way = 2;
	private boolean isGettingData = false;
	@Background
	void getNearbyInfo(boolean clear,int order_way){
		Log.d("Nearby", "getNearbyInfo...");
		synchronized (this) {
			if(isGettingData){
				return ;
			}
			isGettingData = true;
			if(clear){
				page = 1;
			}
			
			Log.d("userCity", userPrefs.userCity().get()+"");
			try {
				initStoreListData(order_way, clear);
				nearbyPrefs.edit().nearbyLastUpdate().put(System.currentTimeMillis()).apply();
				updateListView();
				
				isGettingData = false;
			} catch (Exception e) {
				e.printStackTrace();
				isGettingData = false;
			}
			
		}
	}
	
	public void initShopInfoFromJson(JSONArray jsonArray, boolean clear) throws JsonSyntaxException, JSONException{
		Gson gson = new Gson();
		if(clear){
			stores.clear();
		}
		for(int i=0; i< jsonArray.length(); i++){
			StoreEntivity entivity = gson.fromJson(jsonArray.getString(i).toString(), StoreEntivity.class);
			stores.add(entivity);
		}
		page++;
	}

	
	public void initStoreListData(int ordey_way, boolean clear){
		JSONObject jsonData = new JSONObject();
		JSONResponse jsonResponse = null;
		try {
			jsonData.put("mg_page", page);
			jsonData.put("order_way", ordey_way);
			if(ordey_way == 2){
				jsonData.put("user_long", userPrefs.userLong().get());
				jsonData.put("user_lati", userPrefs.userLatit().get());
				showDistance = true;
			}else{
				jsonData.put("user_id", 499318);
				showDistance = false;
			}
			jsonResponse = JSONUtil.postRequest(52, jsonData);
			if(jsonResponse.getStatus() != Status.ERR){
				JSONObject data = jsonResponse.getData();
				int status = -1;
				status = data.getInt("state");
				if(status == 2){
					JSONArray jsonArray = data.getJSONArray("msgGroupData");
					initShopInfoFromJson(jsonArray, clear);
				}
				
						
			}
		} catch (Exception e) {
			// TODO: handle exception
			
			e.printStackTrace();
		}

	}
	
	@UiThread
	void updateListView() {
		Log.d("Nearby", "updatelistview...");
        mListView.onRefreshComplete();
		
        mListView.setLastUpdate(nearbyPrefs.nearbyLastUpdate().get() );
        adapter.setShowDis(showDistance);

        adapter.notifyDataSetChanged();
        if (stores.size()<2) {
        	Log.d("Nearby", "adapter ...");
        	if(!TextUtils.isEmpty(userPrefs.userCity().get())){
				order_way = 2;
				current = types.NEAR;
				getNearbyInfo(true, order_way);
			}
			else{
				Log.d("userPrefs", userPrefs.userLatit().get()+"/"+userPrefs.userLong().get());
			}
        	return;
        }else{
        	Log.d("Nearby", "adapter >2..");
        }
       
//      if (mPrefs.hasNextPage().get()) {
//			mListView.addFootView(R.layout.uzx_footer);	
//		}
//		else {
//			mListView.removeFootView();
//		}
	}
	
	@UiThread
	void showToast(String msg){
		Toast.makeText(getActivity(), msg+"", Toast.LENGTH_SHORT).show();
	}
	
	@UiThread
	void restoreListView() {
		int pos = nearbyPrefs.listViewSaveState().get();
		mListView.getRefreshableView().setSelection(pos);
	}
	
	@Override
	public void onPause() {
		super.onPause();
		saveListviewState();
	}
	
	@Override
	public void onResume() {
		super.onResume();
		userPrefs = ((MSApp)getActivity().getApplication()).userPrefs;
		initListView();
		updateListView();
		restoreListView();
	}
}
